import { v4 as uuidv4 } from "uuid";
import CryptoJS from 'crypto-js';
let urlTest = 'http://localhost:9999/'
let urlTestV4 = 'http://localhost:996/'
let urlPro = 'https://v3api.sanzhiyun.cn/'
let urlProV4 = 'https://v5api.sanzhiyun.cn/'
let baseUrl = import.meta.env.MODE ==='development' ? urlTest : urlPro
let baseUrlV4 = import.meta.env.MODE === 'development' ? urlTestV4 : urlProV4
import serialize from './obj2str'
import weekday from 'dayjs/plugin/weekday'
import dayjs from "dayjs";
import 'dayjs/locale/zh-cn'
import NP from "number-precision";
import xe from 'xe-utils'
import axios from "axios";
// Toast
import { showToast } from '@nutui/nutui';
import '@nutui/nutui/dist/packages/toast/style/css';

// Notify
import { showNotify } from '@nutui/nutui';
import '@nutui/nutui/dist/packages/notify/style/css';

// Dialog
import { showDialog } from '@nutui/nutui';
import '@nutui/nutui/dist/packages/dialog/style/css';

// ImagePreview
import { showImagePreview } from '@nutui/nutui';
import '@nutui/nutui/dist/packages/imagepreview/style/css';
// // 返回实例，可以手动调用实例中的hide方法关闭提示
// const toast = showToast.loading('在js模块中使用')
// toast.hide()

let loadInstance = null
import sysConfig from "@/config";
import * as qiniu from 'qiniu-js'
dayjs.extend(weekday)
dayjs.locale('zh-cn')
NP.enableBoundaryChecking(false)
const tool = {
	baseUrl: baseUrlV4,
	dayjs: dayjs,
	xe: xe,
	Np: NP,
	// _:_
	// serialize: serialize
}
/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		//加密
		if(sysConfig.LS_ENCRYPTION == "AES"){
			data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
		}
		let cacheValue = {
			content: data,
			datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
		}
		return localStorage.setItem(key, JSON.stringify(cacheValue))
	},
	get(key) {
		try {
			const value = JSON.parse(localStorage.getItem(key))
			if (value) {
				let nowTime = new Date().getTime()
				if (nowTime > value.datetime && value.datetime != 0) {
					localStorage.removeItem(key)
					return null;
				}
				//解密
				if(sysConfig.LS_ENCRYPTION == "AES"){
					value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
				}
				return value.content
			}
			return null
		} catch (err) {
			return null
		}
	},
	remove(key) {
		return localStorage.removeItem(key)
	},
	clear() {
		return localStorage.clear()
	},
	getTenantId () {
		let usr = tool.data.getUser()
		if(usr) {
			return usr.tenantId
		}
		return null
	},
	getUser () {
		let usr = tool.data.get("v4UserInfo")
		if(usr) {
			return usr
		}
		return null;
	},
	getUserId () {
		let usr = tool.data.getUser()
		return usr ? usr.id : null;
	},
	logout() {
		tool.data.remove("v4UserInfo");
		tool.data.remove("v4TOKEN");
		tool.data.remove("v4itemStore");
		tool.data.remove("v4jsonMenuList");
		tool.data.remove("v4MENU");
	},
	setUser (data) {
		tool.data.set('v4UserInfo', data)
		tool.data.set('v4TOKEN', data.token)
	},
	getMenuList () {
		let m = tool.data.get('v4jsonMenuList')
		return m ? m : []
	},
	getToken () {
		return tool.data.get('v4TOKEN')
	}
}
/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}
/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if(isFull){
		if(document.exitFullscreen) {
			document.exitFullscreen();
		}else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		}else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		}else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	}else{
		if(element.requestFullscreen) {
			element.requestFullscreen();
		}else if(element.msRequestFullscreen) {
			element.msRequestFullscreen();
		}else if(element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		}else if(element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}
/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}
tool.dateFormat = function (date, fmt='yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+" : date.getMonth()+1,                 //月份
		"d+" : date.getDate(),                    //日
		"h+" : date.getHours(),                   //小时
		"m+" : date.getMinutes(),                 //分
		"s+" : date.getSeconds(),                 //秒
		"q+" : Math.floor((date.getMonth()+3)/3), //季度
		"S"  : date.getMilliseconds()             //毫秒
	};
	if(/(y+)/.test(fmt)) {
		fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o) {
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;
}
/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if(!num.includes('.')){
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}
/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data){
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data){
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher){
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(data, secretKey, config={}){
			if(secretKey.length % 8 != 0){
				//
			}
			const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return result.toString()
		},
		decrypt(cipher, secretKey, config={}){
			const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return CryptoJS.enc.Utf8.stringify(result);
		}
	}
}
// 组合列表显示 的字段
tool.info = (msg) => {
	showNotify.primary(msg)
}
tool.suc = (msg) => {
	showNotify.success(msg)
}
tool.err = (msg) =>{
	showNotify.danger(msg)
}
tool.warning = (msg) =>{
	showNotify.warn(msg)
}
tool.confirm = (msg, title = '操作提示') => {
	return new Promise((resolve,  ) => {
		showDialog({
			title: title,
			content: msg,
			onOk: () => {
				resolve()
			}
		})
	})
}
tool.uuid = () => {
	return uuidv4();
}
tool.ajax =  (url, data = {}, load = false,) => {
	data.ter = 'cell'
	let token = ''
	let userInfo = tool.data.getUser()
	token = userInfo ? userInfo.token : ''
	postLoading(load, true)
	return axios.post(url, data, {baseURL: baseUrl, headers: {token: token ? token : '', 'Content-Type': 'application/json'}})
		.then(ret => {
			if (ret && ret.data) {
				let data = ret.data
				if (data.stat && data.msg)  tool.suc(data.msg)
				if (!data.stat && data.msg)  tool.err(data.msg)
				return Promise.resolve(data)
			} else {
				tool.err('读取失败')
				return Promise.resolve(false)
			}
		})
		.catch(errs => {
			let r = errs.response
			if (r && r.status && r.status === 401) {
				if (r.data && r.data.msg) {
					tool.err(r.data.msg)
				}
			}
			return Promise.resolve(false)
		}).finally(() => {
			postLoading(load, false)
		})
}
// koa版本
tool.post =  (url, data = {}, load = false, upToken = true) => {
	data.ter = 'cell'
	let token = upToken ? tool.data.get('v4TOKEN') : ''
	postLoading(load, true)
	if(load) {
		setTimeout(() => {
			postLoading(load, false)
		}, 10000)
	}
	let headersObj = {
		'Content-Type': 'application/json',
		token
	}
	return axios.post(url, data, {baseURL: baseUrlV4, headers: headersObj})
		.then(ret => {
			if (ret && ret.data) {
				let data = ret.data
				if (data.stat && data.msg)  tool.suc(data.msg)
				if (!data.stat && data.msg)  {
					tool.err(data.msg)
					if(data.msg === '登录过期,请重新登录') {
						tool.data.logout()
						setTimeout(() => {
							window.location.reload()
						}, 100)
					}
				}
				return Promise.resolve(data)
			} else {
				tool.err('读取失败')
				return Promise.resolve(false)
			}
		})
		.catch(errs => {
			if(errs) {
				let r = errs.response
				if (r && r.status && r.status === 401) {
					if (r.data && r.data.msg) {
						tool.err(r.data.msg)
					}
				}
			}
			return Promise.resolve(false)
		})
		.finally(() => {
			postLoading(load, false)
		})
}
// 关闭ajax加载
const postLoading = (load, val) => {
	if(typeof load === 'boolean') {
		if(load) {
			if (val) {
				showToast.loading('加载中...',{
					duration: 0,
					cover: true
				})
			}
			else {
				setTimeout(() => {
					showToast.hide()
				}, 500)
			}
		}
	}
	else if(typeof load === 'object') {
		if(!xe.isEmpty(load)) {
			if(val) {
				load.loading = true
			}
			else {
				setTimeout(() => {
					load.loading = false
				}, 500)
			}
		}
	}
}
// 时间加减方法
tool.getDay = (day= '', diff = 0, addType = 'day', format = 'YYYY-MM-DD') => {
	return dayjs(day?day:dayjs()).add(diff, addType).format(format)
}
tool.dateFormat = (day, format = 'YYYY-MM-DD') => {
	return  dayjs(day?day:dayjs()).format(format)
}
tool.datetime = (day, format = 'YYYY-MM-DD HH:mm:ss') => {
	return  dayjs(day?day:dayjs()).format(format)
}
// type = beg|end 开始日期|结束日期,diff 加减数量,unit MONTH|DAY|YEAR  current 当前时间
tool.getDayStart = (current = '', type = 'beg', diff = 0, unit = 'MONTH') => {
	if (type === 'beg'){
		return   dayjs(current ? current : dayjs()).add(diff, unit).startOf(unit).format('YYYY-MM-DD')
	}
	if (type === 'end'){
		return   dayjs(current ? current : dayjs()).add(diff, unit).endOf(unit).format('YYYY-MM-DD')
	}
}
//
tool.getBillState = () => {
	return [
		{id:'draft', name: '草稿'},
		{id:'accounted', name: '已记账'},
		{id:'del', name: '已删除'},
		{id:'all', name: '全部'},
	]
}
tool.toolbarAction = (acs = []) => {
	let btn = [
		{name: '新增', code: 'addNew',type: 'text', icon: 'fa fa-plus'},
		{name: '增加', code: 'add',type: 'text', icon: 'fa fa-plus'},
		{name: '记账', code: 'accounted',type: 'text', icon: 'fa fa-rmb',status: 'danger'},
		{name: '编辑', code: 'billEdit', type: 'text',icon: 'fa fa-edit'},
		{name: '重置路线', code: 'resetArea', icon: 'fa fa-map',type: 'text',status: 'danger'},
		{name: '删除', code: 'del',type: 'text', icon: 'fa fa-trash'},
		{name: '打印预览', code: 'printView',type: 'text', icon: 'fa fa-eye'},
		{name: '直接打印', code: 'print',type: 'text', icon: 'fa fa-print'},
		{name: '导数据',icon: 'fa fa-file-o',size: 'small',type: 'text', dropdowns: [
				{name:  '导入数据',size: 'small', code: 'doImport', icon: 'fa fa-cloud-upload'},
				{name:   '下载模板',size: 'small',code: 'downloadMoban', icon: 'fa fa-file-o'}
			]
		},
		{name: '刷新', code: 'refresh',type: 'text', icon: 'fa fa-refresh'},
	]
	let arr = []
	for (let i = 0; i < acs.length; i++) {
		for (let j = 0; j < btn.length; j++) {
			if (acs[i] === btn[j].name) {
				arr.push(btn[j])
			}
		}
	}
	return arr
}
tool.toPrint = (printList, direct = false, isCard = false) => {
	if (printList.length === 0) return tool.err('至少选择 1 行记录进行操作')
	let ids = []
	for (let i = 0; i < printList.length; i++) {
		ids.push(printList[i].id)
	}
	if(ids.length > 20) return tool.err('不能批量打印超过 20 条数据')
	// eslint-disable-next-line no-undef
	const LODOP = (typeof getCLodop==='function') ? getCLodop() : ''
	if (!LODOP) {
		tool.post('common/getPrintUrl', {}).then(ret => {
			if(ret.stat) {
				window.location.href = ret.data
			}
		})
		return tool.info('正在下载打印控件,下载完成后请解压并安装。')
	}
	LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
	LODOP.SET_LICENSES("","C748D766DD08338175E720CB3A546E6C7C8","","");
	tool.ajax('bill/getPrint', {ids: ids , direct: direct, isCard: isCard}).then(ret => {
		if (ret.stat) {
			let data = ret.data
			let evals = data.evals
			let taskId = data.task_id
			for (let i = 0; i < evals.length; i++) {
				let str = evals[i].str
				if (str) {
					eval(str)
				}
				else {
					let data = evals[i].data
					LODOP.ADD_PRINT_TABLE(0,15,'96%','100%', data)
				}
			}
			if (LODOP.CVERSION){
				// eslint-disable-next-line no-undef
				CLODOP.On_Return = (TaskID, Value)=> {
					if (Value !== 0 || Value !== false) {
						tool.post('bill/printSuc', {taskId: taskId}, false).then(() => {})
					}
				}
			}

		}
	})
}
tool.toArrayTree = (ret) => {
	return xe.toArrayTree(ret, { parentKey: "pid", strict: true });
}
tool.toTreeArray = (ret) => {
	return xe.toTreeArray(ret, { clear: true });
}
// 组合查询条件
tool.setSearch = (formData, searchRule) => {
	let where = []
	for (let i in formData) {
		if (i && formData[i]) {
			searchRule.map(s => {
				if (s.field === i) {
					let sop = s.sop ? s.sop : '='
					if (sop === 'include') {
						where.push(` ${i} like '%${formData[i]}%' `)
					}
					else {
						if(s.dataType) {
							if(s.dataType === 'string') {
								if(s.realField) {
									where.push(` ${s.realField} ${s.sop} '${formData[i]}' `)
								}
								else {
									where.push(` ${i} ${s.sop} '${formData[i]}' `)
								}
							}
							else {
								if(s.realField) {
									where.push(` ${s.realField} ${s.sop} ${formData[i]} `)
								}
								else {
									where.push(` ${i} ${s.sop} ${formData[i]} `)
								}
							}
						}
						else {
							if(s.realField) {
								where.push(` ${s.realField} ${s.sop} ${formData[i]} `)
							}
							else {
								where.push(` ${i} ${s.sop} ${formData[i]} `)
							}
						}
					}
				}
			})
		}
	}
	return where
}
// 获取地址 经纬度
tool.getLngLat = (callback, getCurrentLocate = true) => {
	amapLoad(ret => {
		callback(ret)
	}, getCurrentLocate)
}

tool.getMenuByName = (name) => {
	let jsm = tool.data.get('v4jsonMenuList')
	if(jsm) {
		let list = jsm.filter(row => {
			return row.name === name
		})
		return list[0]
	}
	return null
}
tool.callPhone =  (phone) => {
	if(!phone) return tool.warning('无电话号码')
	if(phone.length < 8) return  tool.warning('电话号码不正确')
	tool.confirm(`确定拨打电话 ${phone} ？`, '拨打电话').then(() => {
		if(typeof api !== 'undefined') {
			// eslint-disable-next-line no-undef
			api.call({
				type: 'tel_prompt',
				number: phone
			})
		} else {
			const hr = document.createElement("a")
			hr.href = "tel:" + phone
			hr.click()
		}
	})
}
tool.remoteMenuList = async () => {
	let menu = await getMenuList()
	menu = menu.length > 0 ? tool.toArrayTree(menu) : []
	menu.splice(0, 0, {
		name: 'home', path: '/home', meta: {title: '首页', icon: 'Grid', type: 'menu'},
		children: [
			{
				"name": "dashboard",
				"path": "/dashboard",
				"meta": {
					"title": "控制台",
					"icon": "menu",
					"affix": true
				},
				tag: '首页',
				"component": "home/index"
			},
			{
				"name": "setting",
				"path": "/usercenter",
				"meta": {
					"title": "帐号信息",
					"icon": "user"
				},
				tag: '首页',
				"component": "setting/uc"
			}
		]
	})
	tool.data.set("v4MENU", menu)
	return true
}
tool.setPermission = (type = null, callback) => {
	// let permission = ['camera', 'photos', 'storage', 'location']
	if(type) {
		if(typeof api !== 'undefined') {
			// eslint-disable-next-line no-undef
			api.requestPermission({
				list: type
			}, (res) => {
				if (res.list[0].granted) {
					callback(true)
				}
				else {
					tool.err('授权失败')
					callback(true)
				}
			})
		} else {
			callback(true)
		}
	}
	else {
		callback(true)
	}
}
tool.upToQiniu = async (file, dirName = '', callback) => {
	const ret = await tool.post('common/getUploadToken')
	let maxW = 1200 //global.targetWidth
	let maxH = 1200 //global.targetHeight
	let fileName = dirName + tool.data.getTenantId() + '-' + tool.uuid()
	if(ret.stat && ret.data) {
		const options = {
			quality: 0.9,
			noCompressIfLarger: true,
			maxWidh: maxW,
			maxHeight: maxH
		}
		qiniu.compressImage(file, options).then(data => {
			const observable = qiniu.upload(data.dist, fileName, ret.data)
			observable.subscribe(() => {}, error => {
				if(error.message) {
					tool.err(error.message)
				} else {
					tool.err('上传服务器不用用')
				}
				callback(false)
			}, complete => {
				if(complete && complete.key) {
					let key = complete.key
					callback(key)
				} else {
					callback(false)
				}
			})
		})
	} else {
		callback(false)
	}
}
tool.upToQiniu64 = async (base64, dirName = '', callback) => {
	const ret = await tool.post('common/getUploadToken', {}, true)
	if(ret.stat && ret.data) {
		let fileName = dirName + tool.data.getTenantId() + '-' + tool.uuid()
		let url = "http://upload-z2.qiniup.com/putb64/-1/key/" + btoa(fileName); //非华东空间需要根据注意事项 1 修改上传域名
		let xhr = new XMLHttpRequest();
		xhr.onreadystatechange = () => {
			if (xhr.readyState === 4){
				if(xhr.responseText) {
					let re = JSON.parse(xhr.responseText)
					callback(re.key)
				}
			}
		}
		xhr.open("POST", url, true);
		xhr.setRequestHeader("Content-Type", "application/octet-stream");
		xhr.setRequestHeader("Authorization", 'UpToken ' + ret.data);
		xhr.send(base64);
	} else {
		callback(false)
	}
}
tool.getPicUrl = async (fileName) => {
	let ret = await tool.post('common/getDownUrl', {fileName}, true)
	return ret.data
}
tool.validPhone = (str) => {
	let check = /^1[3-9][0-9]{9}$/.test(str)
	if(!check) {
		tool.err('手机号不正确')
		return false
	}
	return true
}
/** 计算两经纬度之间的距离，单位是m
 * approx distance between two points on earth ellipsoid
 */
tool.getFlatternDistance = (lng1, lat1, lng2, lat2) => {
	let radLat1 = lat1*Math.PI / 180.0;
	let radLat2 = lat2*Math.PI / 180.0;
	let a = radLat1 - radLat2;
	let b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
		Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
	s = s *6378.137 *  1000 ;// EARTH_RADIUS;
	return tool.xe.round(s, 4);
}
const amapLoad = (callback, getCurrentLocate) => {
	// eslint-disable-next-line no-undef
	AMapLoader.load({
		key:"3c8e3c44ae26cd3674ad328c481fc6e3",             // 申请好的Web端开发者Key，首次调用 load 时必填
		// version:"2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
		plugins:['AMap.Geolocation', 'AMap.Geocoder', 'AMap.PlaceSearch'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
	}).then((AMap) => {
		if(getCurrentLocate) {
			let geolocation = new AMap.Geolocation({
				enableHighAccuracy: true, // 是否使用高精度定位，默认：true
				timeout: 10000, // 设置定位超时时间，默认：无穷大
				offset: [10, 20],  // 定位按钮的停靠位置的偏移量
				zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				position: 'RB' //  定位按钮的排放位置,  RB表示右下
			})
			geolocation.getCurrentPosition(function(status,result){
				if(status === 'complete') {
					onComplete(result)
				}
				else {
					onError(result)
				}
			})
			const onComplete = (data) => {
				// data是具体的定位信息
				let lnglat = [data.position.lng, data.position.lat ]
				let geocoder = new AMap.Geocoder()
				geocoder.getAddress(lnglat, (status, result) => {
					if (status === 'complete' && result.info === 'OK') {
						// result为对应的地理位置详细信息
						let obj = {
							lnglat: lnglat,
							address: result.regeocode.formattedAddress,
							citycode: result.regeocode.addressComponent.citycode
						}
						callback(obj)
					} else {
						tool.err('定位失败')
						callback(false)
					}
				})
			}
			const onError = (err) => {
				// 定位出错
				if(err.message.indexOf('denied') !== -1) {
					tool.err('定位授权失败')
				}
				// tool.err('定位失败')
				callback(false)
			}
		}
		else {
			callback(true)
		}
	}).catch(() =>{
		callback(false)
	})
}
const getMenuList = async () => {
	// display的默认全部加载
	let ret = await tool.post('user/getMenuListV4', {})
	if (ret.stat) {
		let data = ret.data
		// let menu = {
		// 	id: -1,
		// 	pid: 0,
		// 	sort: 12,
		// 	icon: 'StarFilled',
		// 	name: '常用'
		// }
		let arr = []
		data.map(row => {
			arr.push({
				id: row.id,
				pid: row.pid,
				tag: row.tag,
				addRoute: row.addRoute,
				name: row.routeName,
				path: '/'+row.path,
				component: row.component,
				meta: {
					title: row.name,
					icon: row.icon,
					type: row.type,
					hidden: !row.display,
					routeName: row.routeName,
					pageName: row.pageName
				}
			})
		})
		tool.data.set('v4jsonMenuList', xe.clone(arr, true))
		return arr
	}
	return []
}
//
tool.obj2str = serialize
tool.str2obj = (str) => {
	return new Function('return ' + str)()
}
tool.addCart = async (cart) => {
	await tool.post('zd/saveCart', {cart})
}
tool.getCartNum = async () => {
	let ret = await tool.post('zd/getCartNum')
	return ret.data
}

tool.updateVer = () => {
	let localVer = tool.data.get('ver') //
	tool.post('app/getVer').then(ret => {
		if(ret.stat) {
			let onlineVer = (ret.data && ret.data.ver)?ret.data.ver:null
			if(localVer) {
				if(onlineVer) {
					if(localVer !== onlineVer) {
						// 本地版本与线上版本不一样，更新
						updateVer(ret)
					}
				}
			}
			else {
				if(onlineVer) {
					// 没有本地版本
					updateVer(ret)
				}
			}
		}
	})
}
const updateVer = (ret) => {
	let msg = ret.data.msg
	let onlineVer = (ret.data && ret.data.ver)?ret.data.ver:null
	tool.confirm(msg, '更新提示' + (ret.data.needLogin?'(需重新登录)':'')).then(() => {
		tool.data.set('ver', onlineVer)
		tool.suc('更新中....')
		if(ret.data.needLogin) {
			tool.data.remove("v4TOKEN");
		}
		window.location.reload()
	})
}

//
export default tool
